<template>
  <a-typography-paragraph v-if="spaceId" type="secondary">
    保存至空间：<a :href="`/space/${spaceId}`" target="_blank">{{ spaceId }}</a>
  </a-typography-paragraph>

  <div class="url-picture-upload">
    <a-input-group compact style="margin-bottom: 16px">
      <a-input v-model:value="fileUrl" style="width: calc(100% - 120px)" placeholder="请输入图片 URL" />
      <a-button type="primary" :loading="loading" @click="handleUpload" style="width: 120px">提交</a-button>
    </a-input-group>
    <img v-if="picture?.url" :src="picture?.url" alt="avatar" />
  </div>

</template>

<script lang="ts" setup>

import { message } from 'ant-design-vue'
import { computed, ref } from 'vue'
import { uploadPictureByUrlUsingPost } from '@/api/pictureController'
import type { Props } from 'ant-design-vue/es/form/useForm'
import { useRoute } from 'vue-router'
const props = defineProps<Props>()
const loading = ref<boolean>(false)
const fileUrl = ref<string>()
const route = useRoute();
// 空间 id
const spaceId = computed(() => {
  return route.query?.spaceId
})
interface Props {
  picture?: API.PictureVO
  spaceId?: number
  onSuccess?: (newPicture: API.PictureVO) => void
}


/**
 * 上传
 */
const handleUpload = async () => {
  loading.value = true
  try {
    const params: API.PictureUploadDTO = { url: fileUrl.value}
    params.spaceId = spaceId.value
    if (props.picture) {
      params.id = props.picture.id
    }
    const res = await uploadPictureByUrlUsingPost(params)
    if (res.data.code === 0 && res.data.data) {
      message.success('图片上传成功')
      // 将上传成功的图片信息传递给父组件
      props.onSuccess?.(res.data.data)
    } else {
      message.error('图片上传失败，' + res.data.msg)
    }
  } catch (error) {
    message.error('图片上传失败')
  } finally {
    loading.value = false
  }
}



</script>

<style scoped>

</style>
